﻿using HpxWMS_Api.Models;
using HpxWMS_Api.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace HpxWMS_Api.CustomAttribute
{
    /// <summary>
    /// 授权过滤器，校验是否经过授权了
    /// </summary>
    public class ApiAuthorizeAttribute : AuthorizeAttribute
    {
        
        /// <summary>
        /// 判断是否已授权
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            return true;
            //判断前端是否有传递token
            if (actionContext.Request.Headers.Authorization == null)
            {
                return false;
            }

            var scheme = actionContext.Request.Headers.Authorization.Scheme;
            var token = actionContext.Request.Headers.Authorization.Parameter;
            if (scheme != "Bearer" || token == null)
            {
                return false;
            }
            // 解析校验 
            var authInfo = JwtHelper<AuthInfo>.AnalyzeJwt(token);
            if (authInfo == null)
            {
                return false;
            }
            // 过期
            if (authInfo.ExpiredTime < DateTime.Now)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 处理未授权时，服务器返回的结果
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
        }


    }
}